package io.hellsinger.vortex.ui.screen.storage.list

import io.hellsinger.viewmodel.VortexViewModel
import io.hellsinger.vortex.data.model.PathItem
import io.hellsinger.vortex.data.model.PendingTransition
import io.hellsinger.vortex.data.model.PendingTransition.Companion.TYPE_COPY
import io.hellsinger.vortex.data.model.PendingTransition.Companion.TYPE_MOVE
import io.hellsinger.vortex.domain.model.Transition
import io.hellsinger.vortex.domain.repository.StorageRepository
import io.hellsinger.vortex.ui.component.adapter.SuperItem
import io.hellsinger.vortex.ui.component.adapter.title
import io.hellsinger.vortex.ui.screen.storage.list.StorageListMenuTaskViewModel.MutableUiState
import io.hellsinger.vortex.ui.screen.storage.list.StorageListMenuTaskViewModel.UiState
import kotlinx.coroutines.flow.launchIn
import kotlinx.coroutines.flow.onEach

class StorageListMenuTaskViewModel(
    private val repository: StorageRepository,
) : VortexViewModel<UiState, MutableUiState>(
        scopeName = "Storage List Menu Task Scope",
    ) {
    override val state: MutableUiState = MutableUiState()

    fun collectSharedState() =
        intent { state ->
            repository
                .getPendingTransitions()
                .onEach { transitions ->
                    val groups =
                        transitions.groupBy { pending ->
                            when (pending) {
                                is Transition.Move -> "Move"
                                is Transition.Copy -> "Copy"
                            }
                        }

                    state.updateItems {
                        groups.forEach { (group, transitions) ->
                            title(group)
                            addAll(
                                transitions.map { transition ->
                                    val sources = transition.sources.map { path -> PathItem(path) }
                                    when (transition) {
                                        is Transition.Copy -> PendingTransition(sources, TYPE_COPY)
                                        is Transition.Move -> PendingTransition(sources, TYPE_MOVE)
                                    }
                                },
                            )
                        }
                    }
                    update(0)
                }.launchIn(this)
        }

    fun removePending(transition: Transition) =
        intent {
            repository.removePending(transition)
        }

    interface UiState {
        val items: List<SuperItem>
    }

    class MutableUiState(
        override val items: MutableList<SuperItem> = mutableListOf(),
    ) : UiState {
        fun updateItems(block: MutableList<SuperItem>.() -> Unit) {
            items.clear()
            items.apply(block)
        }
    }
}
